
import 'package:sqflite/sqflite.dart';

class DeviceModel {
  String? id;
  String? name;
  String? status;
  DeviceModel({this.id, this.name, this.status});
  factory DeviceModel.fromJson(Map<String, dynamic> json) {
    return DeviceModel(
      id: json['id'],
      name: json['name'],
      status: json['status'],
    );
  }
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'name': name,
      'status': status,
    };
  }
  static Future<void> insert(DeviceModel device) async {
    final db = await openDatabase('data.db');
    await db.insert(
      'device',
      device.toJson(),
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
    await db.close();
  }
  static Future<List<DeviceModel>> getAll() async {
    final db = await openDatabase('data.db');
    final List<Map<String, dynamic>> maps = await db.query(
      'device',
      orderBy: 'id DESC',
      limit: 1,
    );
    await db.close();
    return List.generate(maps.length, (i) {
      return DeviceModel.fromJson(maps[i]);
    });
  }
  static Future<void> connected(String id) async {
    final db = await openDatabase('data.db');
    await db.update(
      'device',
      {'status': 0},
      where: '1 == 1',
    );
    await db.update(
      'device',
      {'status': 1},
      where: 'id == ?',
      whereArgs: [id],
    );
    await db.close();
  }

  static Future<void> disconnected(String id) async {
    final db = await openDatabase('data.db');
    await db.update(
      'device',
      {'status': 0},
      where: 'id == ?',
      whereArgs: [id],
    );
    await db.close();
  }
  static Future<void> delete(String id) async {
    final db = await openDatabase('data.db');
    await db.delete(
      'device',
      where: 'id = ?',
      whereArgs: [id],
    );
    await db.close();
  }
  static Future<DeviceModel?> getLastConnected() async {
    final db = await openDatabase('data.db');
    final List<Map<String, dynamic>> maps = await db.query(
      'device',
      where: 'status = ?',
      whereArgs: [1],
      orderBy: 'id DESC',
      limit: 1,
    );
    await db.close();
    return maps.isNotEmpty ? DeviceModel.fromJson(maps.first) : null;
  }

}
